//
//  HLELowcostUtil.m
//  HLELowcostPeripherial
//
//  Created by hle1 on 2021/5/4.
//

#import "HLELowcostUtil.h"

@implementation HLELowcostUtil

+ (void)string:(NSString *)string toBytes:(unsigned char *)bytes {
    for (int i = 0; i != string.length/2; ++i) {
        NSString *firstChar = [NSString stringWithFormat:@"%c", [string characterAtIndex:i*2]], *secondChar = [NSString stringWithFormat:@"%c", [string characterAtIndex:i*2+1]];
        unsigned char firstHex = [self indexOfHexChar:firstChar], secondHex = [self indexOfHexChar:secondChar];
        bytes[i] = (firstHex << 4)|secondHex;
    }
}

+ (unsigned char)indexOfHexChar:(NSString *)hexChar {
    for (int i = 0; i != [self HEXs].count; ++i) {
        if ([hexChar isEqualToString:[[self HEXs] objectAtIndex:i]])
            return i;
    }
    return 0;
}

+ (NSString *)getStringFromBytes:(Byte*)bytes ofLength:(int)length{
    NSMutableString* res = [NSMutableString string];
    for (int i = 0; i != length; ++i) {
        int h = bytes[i]>>4, l = bytes[i]&0x0f;
        [res appendString:[[self HEXs] objectAtIndex:h]];
        [res appendString:[[self HEXs] objectAtIndex:l]];
        [res appendString:@" "];
    }
    return [res copy];
}

+ (NSArray <NSString *>*)HEXs
{
    return @[@"0", @"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", @"A", @"B", @"C", @"D", @"E", @"F"];
}

@end
